package com.lebang.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lebang.entity.task.LbbCommon;
import com.lebang.mapper.LbbCommonMapper;
import com.lebang.model.excel.CommonExcel;
import com.lebang.service.buss.MemberRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author: hwq
 * @Date: 2019/11/28 14:21
 * @Version 1.0
 */
@Controller
@RequestMapping("/export/excel")
public class ExportRecordExcel {
    @Autowired
    private MemberRecordService memberRecordService;
    @Autowired
    private LbbCommonMapper lbbCommonMapper;


    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link }
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String taskId, String category,
                         String str,
                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date star,
                         @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date end) throws IOException {

        Optional<LbbCommon> common= Optional.ofNullable(lbbCommonMapper.getByTaskId(taskId));
        List<String> strings = Arrays.asList(str.split(","));
        List<CommonExcel> list = memberRecordService.selectByTaskIdAndCategory(taskId, category, strings, star, end);
        if (list.size() == 0) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; CHARSET=utf-8");
            String json = JSONObject.toJSONString("没有数据");
            PrintWriter out = response.getWriter();
            out.print(json);
            out.flush();
            out.close();
            return;
        }
        List<List<Object>> data = new ArrayList<>();
        List<List<String>> head = this.head(1);
        CommonExcel vo = list.get(0);
        JSONArray item = JSON.parseArray(vo.getResult());
        if (item != null) {
            for (int i = 0; i < item.size(); i++) {
                List<String> head1 = new ArrayList<String>();
                if (item.getJSONObject(i).getJSONObject("resultImage") != null) {


                    head1.add("截图" + i);
                    head.add(head1);

                }
                if (item.getJSONObject(i).getString("resultInput") != null) {

                    head1 = new ArrayList<>();
                    head1.add("用户上传" + i);
                    head.add(head1);

                }
            }
        }

        list.forEach(s -> {
            List<Object> objects = new ArrayList<>();
            if ("CheckSuccess".equals(s.getStatus())) {
                objects.add("审核成功");
            } else if ("WaitCheckout".equals(s.getStatus())) {
                objects.add("等待审核");
            } else if ("CheckFailure".equals(s.getStatus())) {
                objects.add("审核失败");
            } else {
                objects.add(s.getStatus());
            }
            objects.add(s.getDate());
            objects.add(s.getPhone());
            objects.add(s.getImei());
            JSONArray jsonObject = JSON.parseArray(s.getResult());
            if (jsonObject != null) {
                for (int i = 0; i < jsonObject.size(); i++) {
                    if (jsonObject.getJSONObject(i).getJSONObject("resultImage") != null) {


                        objects.add(jsonObject.getJSONObject(i).getJSONObject("resultImage").getString("image"));

                    }
                    if (jsonObject.getJSONObject(i).getString("resultInput") != null) {

                        objects.add(jsonObject.getJSONObject(i).getString("resultInput"));

                    }
                }
                s.setResult("");
            }
            data.add(objects);
        });
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        LocalDate localDateTime = LocalDate.now();
        String title=common.map(LbbCommon::getTitle).orElse("");
        String fileName = URLEncoder.encode(localDateTime.format(DateTimeFormatter.ISO_DATE)+":"+title, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //EasyExcel.write(response.getOutputStream(), CommonExcel.class).sheet("数据").doWrite(list);
        EasyExcel.write(response.getOutputStream())
                // 这里放入动态头
                .head(head).sheet("模板")
                // 当然这里数据也可以用 List<List<String>> 去传入
                .doWrite(data);
    }

    @GetMapping("/list")
    public String list(String taskId, Model model) {
        model.addAttribute("taskId", taskId);
        return "/export/list";
    }

    private List<List<String>> head(int size) {
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<String>();
        head0.add("审核结果");
        List<String> head1 = new ArrayList<String>();
        head1.add("任务提交时间");
        List<String> head2 = new ArrayList<String>();
        head2.add("手机号码");
        List<String> head3 = new ArrayList<String>();
        head3.add("设备标识");
        list.add(head0);
        list.add(head1);
        list.add(head2);
        list.add(head3);
        return list;
    }
}
